<?php
class RegisterModel extends CustomModel
{

    public function usernameInUse($username)
    {
        $usersAbm = new ABM('users');
        return $usersAbm->get(array('username' => $username, 'user_status' => array(STATUS_ONLINE, STATUS_PENDING)));
    }

    public function emailInUse($email)
    {
        $usersAbm = new ABM('users');
        return $usersAbm->get(array('email' => $email, 'user_status' => array(STATUS_ONLINE, STATUS_PENDING)));
    }

    public function getPendingUser($idUser)
    {
        $usersAbm = new ABM('users');
        $join = array(
            'profiles' => array('users.iduser' => 'profiles.fkuser')
        );
        return $usersAbm->getWithJoin(array('iduser' => $idUser, 'user_status' => array(STATUS_PENDING)), $join);
    }

    public function createUser($userData, $profileData, $confirmLink)
    {
        // Begin transaction
        $this->db->beginTransaction();
        // Instance Abm's helpers
        $usersAbm    = new ABM('users');
        $profilesAbm = new ABM('profiles');
        // Password encrypt luego del insert
        $password = $userData['password'];
        $userData['password'] = 'CHANGEME';
        // Insert user data
        $userData['user_type']   = USER_TYPE_NORMAL;
        $userData['user_status'] = STATUS_PENDING;
        if ($idUser = $usersAbm->insert($userData)) //El insert ID lo devuelve el framework con nun nautoincremental
        {
            // Insert profile data
            $profileData['fkuser'] = $idUser;
            if ($profilesAbm->insert($profileData, false))
            {
                do
                {
                    $token = $this->generateToken($idUser);
                } while($this->tokenExists($token));
                $pending = array(
                    'fkuser'             => $idUser,
                    'token'              => $token,
                    'creation_timestamp' => time(),
                    'status'             => STATUS_PENDING
                );
                $pendignUsersAbm = new ABM('pending_users');
                if($pendignUsersAbm->insert($pending))
                {
                    // Enviar mail
                    $to      = $userData['email'];
                    $link    = $confirmLink.$token;
                    $subject = $profileData['fname'].' te damos la bienvenida a SETU';
                    $message = "Hola {$profileData['fname']} {$profileData['lname']}!\n\n"
                              ."Hemos recibido una solicitud de parte suya para registrarse en SETU. Para poder finalizar su registro por favor siga este enlace {$link} y active su cuenta."
                              ."\n\nEl equipo de SETU";
                    $headers = 'From: setucaece@gmail.com' . "\r\n" .
                               'Reply-To: setucaece@gmail.com' . "\r\n" .
                               'X-Mailer: PHP/' . phpversion();
                    mail($to, $subject, $message, $headers);
                    // Actualizar password
                    $encripted = $this->encryptPassword($idUser, $password);
                    $usersAbm = new ABM('users');
                    $uData = array('password' => $encripted);
                    if ($usersAbm->update(array('iduser' => $idUser), $uData))
                    {
                        // Commit y return
                        $this->db->commitTransaction();
                        return true;
                    }
                    else
                    {
                        $this->db->rollbackTransaction();
                        return false;
                    }
                }
                else
                {
                    $this->db->rollbackTransaction();
                    return false;
                }
            }
            else
            {
                $this->db->rollbackTransaction();
                return false;
            }
        }
        else
        {
            $this->db->rollbackTransaction();
            return false;
        }
    }

    public function generateToken($idUser)
    {
        $seed = "$37u_pr0j3c87";
    	return sha1($seed.$idUser.md5($idUser.$seed).microtime());
    }

    public function tokenExists($token)
    {
    	$pendignUsersAbm = new ABM('pending_users');
    	return $pendignUsersAbm->get(array('token' => $token));
    }

    public function getAvailableToken($token)
    {
        $pendignUsersAbm = new ABM('pending_users');
        $tokenFilter = new dbFilter('token', '=' , $token);
        $statusFilter = new dbFilter('status', '=' , STATUS_PENDING);
        $dateFilter = new dbFilter('creation_timestamp', '>=' , time()-(60*60*24*7));
        $filter = new dbFilter($tokenFilter, 'AND' , $statusFilter);
        $filter = new dbFilter($filter, 'AND', $dateFilter);
        return $pendignUsersAbm->get($filter,false,false,false);
    }

    public function activateUser($fkUser, $idPending, $password = false, $userData)
    {
        $this->db->beginTransaction();
        $abmUsuario = new ABM('users');
        if($abmUsuario->update(array('iduser' => $fkUser), array('user_status' => STATUS_ONLINE)))
        {
            // Si esta actualizando la password
            if ($password)
            {
                // Actualizar password
                $encripted = $this->encryptPassword($fkUser, $password);
                $usersAbm = new ABM('users');
                $uData = array('password' => $encripted);
                if ($usersAbm->update(array('iduser' => $fkUser), $uData))
                {
                    // Actualizar pending
                    $pendignUsersAbm = new ABM('pending_users');
                    if($pendignUsersAbm->update(array('idpending_user' => $idPending ), array('used_timestamp' => time(), 'status' => STATUS_ONLINE)))
                    {
                        $usuariosModel = new UsuariosModel();
                        // Commit
                        $this->db->commitTransaction();
                        // Enviar mail de confirmacion de activacion de cuenta
                        $to      = $userData['email'];
                        $subject = $userData['fname'].' '.$userData['lname'].' ha sido confirmado en SETU';
                        $message = "Hola {$userData['fname']} {$userData['lname']}!\n\n"
                                  ."Estos son sus datos de acceso para ingresar a SETU:\n"
                                  ."Nombre: ".$userData['fname']."\n"
                                  ."Apellido: ".$userData['lname']."\n"
                                  ."Nombre usuario: ".$userData['username']."\n"
                                  ."Email: ".$userData['email']."\n"
                                  ."Token de acceso: ".$userData['user_secret']."\n"
                                  ."Ver QR: ".$usuariosModel->getOcrUrl($userData['username'], $secret)."\n"
                                  ."\n\nEl equipo de SETU";
                        $headers = 'From: setucaece@gmail.com' . "\r\n" .
                                   'Reply-To: setucaece@gmail.com' . "\r\n" .
                                   'X-Mailer: PHP/' . phpversion();
                        mail($to, $subject, $message, $headers);
                        // Return
                        return true;
                    }
                    else
                    {
                        $this->db->rollbackTransaction();
                        return false;
                    }
                }
                else
                {
                    $this->db->rollbackTransaction();
                    return false;
                }
            }
            else
            {
                $pendignUsersAbm = new ABM('pending_users');
                if($pendignUsersAbm->update(array('idpending_user' => $idPending ), array('used_timestamp' => time(), 'status' => STATUS_ONLINE)))
                {
                    $this->db->commitTransaction();
                    return true;
                }
                else
                {
                    $this->db->rollbackTransaction();
                    return false;
                }
            }
        }
        else
        {
            $this->db->rollbackTransaction();
            return false;
        }
    }

    public function encryptPassword($idUser, $password)
    {
        $seed = '__$37U_()P4$$3nCrypT###SEED';
        return sha1(md5(md5($idUser.$seed.$password).$idUser).$password);
    }

}
?>